package com.hawk.eye.client.logback.appender.http;

import com.hawk.eye.client.logback.appender.HawkEyeBaseAppender;
import com.hawk.eye.client.logback.appender.IHawkEyeAppender;
import com.hawk.eye.client.toolkit.HawkEyeLogger;
import com.hawk.eye.client.toolkit.ServiceAuthHolder;
import com.hawk.eye.client.client.*;
import com.hawk.eye.common.client.IClient;
import com.hawk.eye.common.client.JdkHttpClient;
import com.hawk.eye.common.client.OkHttpClient;
import com.hawk.eye.common.constant.HttpStatus;
import com.hawk.eye.common.constant.RequestUrlConstant;
import com.hawk.eye.common.core.ApiResult;
import com.hawk.eye.common.model.ServiceAuthData;
import com.hawk.eye.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @className: HawkEyeHttpErrorAppender
 * @description: HawkEye基于Http对ERROR级别日志进行告警推送的appender
 * @author: salad
 * @date: 2023/10/8
 **/
@Slf4j
public class HawkEyeHttpErrorAppender<E> extends HawkEyeBaseAppender<E> implements IHawkEyeAppender {

    private IClient client = new OkHttpClient();

    @Override
    public void start() {
        if (client == null){
            addError("IClient不能为空");
        }
        super.start();
    }

    @Override
    public void send(RequestParam requestParam) {
        try {
            String serverAddr = ServiceAuthHolder.getServerAddr();
            //请求HawkEyeServer进行告警推送
            String json = client.pushLogMessage(RequestUrlConstant.PUSH_ALARM_DATA_URI.formatUri(serverAddr),
                    null, JsonUtil.toJson(requestParam));
            ApiResult result = JsonUtil.parse(json, ApiResult.class);
            //输出异常日志，需要防止告警死循环
            if (result != null && result.getCode() != HttpStatus.SUCCESS) {
                HawkEyeLogger.errorWithSkipSend(this.getClass(), "HawkEyeClient请求HawkEyeServer异常:" + result.getMsg());
            }
        } catch (Throwable e) {
            //输出异常日志，需要防止告警死循环
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "HawkEyeClient请求HawkEyeServer异常:" + e.getMessage(), e);
        }
    }

    public IClient getClient() {
        return client;
    }

    public void setClient(String className) {
        try {
            this.client = (IClient) Class.forName(className).newInstance();
        } catch (Exception e) {
            this.client = new JdkHttpClient();
            //输出异常日志，需要防止告警死循环
            HawkEyeLogger.errorWithSkipSend(this.getClass(), "实例化IClient失败,将使用默认IClient[JdkHttpClient],请确认设置的IClient类路径是否正确::" + e.getMessage(), e);
        }
    }

}